package com.kfpanda.spring.batch.listener;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.commons.io.IOUtils;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.listener.JobExecutionListenerSupport;
import org.springframework.beans.factory.annotation.Value;

import com.util.common.FilePath;

public class PropFileIncremJobListener extends JobExecutionListenerSupport{
	
	@Value("${prop.file.incrementer.path}")
	private String propFilePath = FilePath.getAbsolutePathWithClass() + "properties/incrementer.properties";
	
	@Override
	public void beforeJob(JobExecution jobExecution) {
		Properties prop = new Properties();
		FileInputStream input = null;
		try {
			input = new FileInputStream(new File(this.propFilePath));
			prop.load(input);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(input);
		}
		String jobName = jobExecution.getJobInstance().getJobName();
		String incrementer = prop.getProperty(jobName, "0");
		jobExecution.getExecutionContext().put("incrementer", incrementer);
	}

	@Override
	public synchronized void afterJob(JobExecution jobExecution) {
		/*Integer runId = jobExecution.getVersion();
		System.out.println("=====================  version: " + runId + "====endTime:" + jobExecution.getEndTime()+ "==================");
		jobExecution.stop();
		ForumInput forumInput = (ForumInput)jobExecution.getExecutionContext().get("forumInput");
		Object guidDate = jobExecution.getExecutionContext().get("guidDate");
		if( guidDate != null ){
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String lastGuid = format.format(guidDate);
			if(lastGuid.compareTo(forumInput.getLastGuid()) > 0){
				Map<String, Object> valueMap = new HashMap<String, Object>();
				valueMap.put("sconf", forumInput.getSconf());
				valueMap.put("inputType", forumInput.getInputType());
				valueMap.put("lastGuid", lastGuid);
				forumInputDao.updateEntity(valueMap);
			}
		}*/
		Properties prop = new Properties();
		File file = new File(this.propFilePath);
		FileInputStream input = null;
		try {
			input = new FileInputStream(file);
			prop.load(input);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(input);
		}
		String jobName = jobExecution.getJobInstance().getJobName();
		prop.setProperty(jobName, jobExecution.getExecutionContext().getString("incrementer"));
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			prop.store(out, "batch incrementer");
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			IOUtils.closeQuietly(out);
		}
	}
	
}
